package thread;

/*
 * @author zzr
 * @date: 2025/04/18  14:22
 * @description:
 */

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class MyThreadPoolExecutor {

    // List 数据结构来存储线程
    private List<Thread> threadList = new ArrayList<>();

    // 是一个用来保存任务的队列
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);

    // 通过 n 来指定要创建的线程的个数
    public MyThreadPoolExecutor (int n) {
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(() -> {
                // 线程要做的事情是：把任务队列中的任务不停的取出来，并且进行执行~
                while (true) {
                    Runnable runnable = null;
                    try {
                        runnable = queue.take();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    runnable.run();
                }
            });

            t.start();
            threadList.add(t);
        }
    }
    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);
    }
}
public class Thread26 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPoolExecutor executor = new MyThreadPoolExecutor(4);
        for (int i = 0; i < 1000; i++) {
            int n = i;
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("执行任务 " + n + "当前线程为 " + Thread.currentThread().getName());
                }
            });
        }
    }
}
